import utils from '../../utils/util';
var api = require('../../api.js');
var app = getApp();
var share_count = 0;
var pageNum = 1;
var inviteCode = ''
var isFinish = false

Page({
  data: {
    imgServer: api.default.img_server,
    tab_cat_list: [],
    banner_list: [],
    productList: [],
    article_list: [],
    x: wx.getSystemInfoSync().windowWidth,
    y: wx.getSystemInfoSync().windowHeight
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    pageNum = 1;
    isFinish = false;
    this.data.productList = [];
    app.request({
      url: api.default.article_list,
      data: {
      },
      success: function (res) {
        wx.hideLoading();
        page.setData({
          article_list: res.data.list,
        });
      }
    });


    var scene = decodeURIComponent(options.scene);
    console.log("scene======");
    console.log(scene);
      inviteCode = options.user_id != undefined ? options.user_id : ""
    var access_token = wx.getStorageSync("access_token");
    if (inviteCode != undefined & inviteCode != '') {
      wx.setStorageSync('inviteCode', inviteCode)
      console.log("invitecode==========" + inviteCode)
      this.updateMemberInviteCode()
    }else  if(scene !=null && scene != undefined){
      inviteCode = scene
      wx.setStorageSync('inviteCode', inviteCode)
      console.log("invitecode==========" + inviteCode)
      this.updateMemberInviteCode()
    }
    console.log('token:' + access_token);
    // if (!access_token)
    // app.login();
    console.log('login-token:' + access_token);
    this.loadData(options);
 
    var page = this;
    var parent_id = 0;
    var user_id = options.user_id;
    var scene = decodeURIComponent(options.scene);
    if (user_id != undefined) {
      parent_id = user_id;
    } else if (scene != undefined) {
      parent_id = scene;
    }
  },

  /**
   * 加载页面数据
   */
  loadData: function(options) {
    var page = this;
    page.loadCatListData();
    this.getList();
    this.getBannerList();
  },

  ///获取分页数据列表
  getList() {
    var that = this;
    app.request({
      url: api.default.indexList,
      data: {
        pageNum: pageNum,
        pageSize: 1
      },
      success: function(res) {
        if (res.code == 200) {
          console.log(res.data)
          that.setData({
            productList: pageNum == 1 ? res.data.list : that.data.productList.concat(res.data.list)
          });
          if (pageNum < res.data.totalPage - 1) {//这里减一是为了不显示最后一个分类
            pageNum++;
            //todo 这里可以做一次判断，确保每次请求的是当页的数据
          } else {
            isFinish = true
          }
        }
      },
      complete: function() {
        wx.stopPullDownRefresh();
      }
    });
  },
  ///获取banenr
  getBannerList() {
    var that = this;
    app.request({
      url: api.default.bannerList,
      success: function (res) {
        if (res.code == 200) {
          console.log("banner"+res.data)
          that.setData({
            banner_list: res.data.list
          });
        }
      },
      complete: function () {
        // wx.stopPullDownRefresh();
      }
    });
  },

  loadCatListData: function() {
    var page = this;
    var tab_cat_list = wx.getStorageSync("cat_list");
    if (tab_cat_list) {
      page.setData({
        tab_cat_list: tab_cat_list,
      });
    }
    app.request({
      url: api.default.cat_list,
      success: function(res) {
        if (res.code == 200) {
          page.setData({
            tab_cat_list: res.data,
          });
          wx.setStorageSync("cat_list", res.data);
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    share_count = 0;
    var store = wx.getStorageSync("store");
    if (store && store.name) {
      wx.setNavigationBarTitle({
        title: store.name,
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    pageNum = 1;
    isFinish = false;
    this.data.productList = [];
    this.getList();

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (isFinish) return
    this.getList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(options) {
    var page = this;
    var user_info = wx.getStorageSync("my_info");
    return {
      path: "/pages/index/index?user_id=" + user_info.id,
      success: function(e) {
        share_count++;
        if (share_count == 1)
          app.shareSendCoupon(page);
      }
    };
  },

  receive: function(e) {
    var page = this;
    var id = e.target.dataset.index;
    wx.showLoading({
      mask: true,
    });
    if (!page.hideGetCoupon) {
      page.hideGetCoupon = function(e) {
        var url = e.currentTarget.dataset.url || false;
        page.setData({
          get_coupon_list: null,
        });
        if (url) {
          wx.navigateTo({
            url: url,
          });
        }
      };
    }

  },


  navigatorClick: function(e) {
    var page = this;
    var open_type = e.currentTarget.dataset.open_type;
    var url = e.currentTarget.dataset.url;
    if (open_type != 'wxapp')
      return true;
    //console.log(url);
    url = parseQueryString(url);
    url.path = url.path ? decodeURIComponent(url.path) : "";
    console.log("Open New App");
    wx.navigateToMiniProgram({
      appId: url.appId,
      path: url.path,
      complete: function(e) {
        console.log(e);
      }
    });
    return false;

    function parseQueryString(url) {
      var reg_url = /^[^\?]+\?([\w\W]+)$/,
        reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
        arr_url = reg_url.exec(url),
        ret = {};
      if (arr_url && arr_url[1]) {
        var str_para = arr_url[1],
          result;
        while ((result = reg_para.exec(str_para)) != null) {
          ret[result[1]] = result[2];
        }
      }
      return ret;
    }
  },
  tabCatClick: function(e) {
    wx.setStorageSync("indexId", e.currentTarget.dataset.indexid);
    wx.switchTab({
      url: '/pages/cat/cat',
    });
  },
  closeCouponBox: function(e) {
    this.setData({
      get_coupon_list: ""
    });
  },
  goCoupons: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  
  },
  updateMemberInviteCode: function(e) {
    var page = this;
    var user_info = wx.getStorageSync("user_info");
    var my_info = wx.getStorageSync("my_info");
    console.log(my_info);
    var test = {};
    test.wxId = wx.getStorageSync("access_token");
    test.id = wx.getStorageSync("my_info").id;
    if (inviteCode != undefined & inviteCode != '') {
      test.invitecode = inviteCode;
    }


    //绑定推广人ID
    app.request({
      url: api.order.updateMember,
      method: 'POST',
      data: test,
      success: function(res) {
        console.log("====------" + res)
        if (res.code == 200) {

        } else {


        }
      }
    });
  },
});